import pyautogui
import time
import numpy as np
import cv2
import platform
import subprocess

time.sleep(2)

pyautogui.PAUSE = 0.5 # 设置自动化操作时间间隔

pyautogui.locateOnScreen

print('开始')

# precision 越高，容忍度越低，发现的误报次数越少，默认值为 0.8
def imagesearch(image, precision=0.8):
    im = pyautogui.screenshot()
    is_retina = False
    if platform.system() == "Darwin": # MacOS
        is_retina = subprocess.call("system_profiler SPDisplaysDataType | grep 'retina'", shell=True)
    if is_retina:
        im.thumbnail((round(im.size[0] * 0.5), round(im.size[1] * 0.5)))
    # im.save('testarea.png') useful for debugging purposes, this will save the captured region as "testarea.png"
    img_rgb = np.array(im)
    img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
    template = cv2.imread(image, 0)
    template.shape[::-1]

    res = cv2.matchTemplate(img_gray, template, cv2.TM_CCOEFF_NORMED)
    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
    if max_val < precision:
        print(max_val)
        return [-1, -1]
    return max_loc



def delete_chat_info():
    '''删除聊天信息'''

    pyautogui.screenshot() # 屏幕截图
    # 定位聊天气泡图
    chat_bubble = pyautogui.locateCenterOnScreen('people.png')
    # chat_bubble = imagesearch('people.png', 0.4)

    if not chat_bubble:
        print('定位聊天气泡图失败')
        return
    print('chat_bubble', chat_bubble)
    # 聊天气泡图右移100像素则是联系人的坐标位置
    x = chat_bubble[0]/1.78 + 150
    y = chat_bubble[1]/1.78 + 20
    # 右键点击，让微信弹窗删除列表框
    # pyautogui.click(x=x, y=y, button='right')
    pyautogui.rightClick(x, y)

    pyautogui.screenshot()
    # 定位删除按钮
    delete_button = pyautogui.locateCenterOnScreen('delete.png')
    if not delete_button:
        delete_button = pyautogui.locateCenterOnScreen('delete2.png')
        if not delete_button:
            print('定位删除按钮失败')
            return
    # delete_button = imagesearch('delete.png')
    print('delete_button', delete_button)
    # 模拟鼠标点击删除按钮
    x = delete_button[0]
    y = delete_button[1]
    pyautogui.click(x/1.78, y/1.78)

def test():
    for i in range(3):
        delete_chat_info()

def test2():

    res = imagesearch('people.png', 0.6)
    print(res)
    # res = imagesearch('delete.png', 0.6)
    # print(res)

def get_chat_bubble():
    pyautogui.screenshot() # 屏幕截图
    # 定位聊天气泡图
    chat_bubble = pyautogui.locateOnScreen('people.png', confidence=0.4)
    print(chat_bubble)

test2()
get_chat_bubble()

# test()